<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends BaseController
{

    public $model = User::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $model = new $this->model;
        $nickname = $request->input('nickname');
        $is_vip = $request->input('is_vip', -1);
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $is_black = $request->input('is_black', -1);
        $input = $request->input();
        $benefit_user = $input['benefit_user'] ?? User::BENEFIT_DAREN;
        $is_daren = $request->input('is_daren', -1);
        $is_temp_daren = $request->input('is_temp_daren', -1);

        $users = $model->NickName($nickname)
            ->when($benefit_user, function ($q) use($benefit_user) {
                $q->where('benefit_user', $benefit_user);
            })
            ->isVip($is_vip)
            ->startAt($start_at)
            ->endAt($end_at)
            ->when($is_daren != -1, function ($q) use($is_daren){
                $q->where('is_daren', $is_daren);
            })
            ->when($is_temp_daren != -1, function ($q) use($is_temp_daren){
                $q->where('is_temp_daren', $is_temp_daren);
            })
            ->black($is_black)
//            ->withCount('notebook', 'collect_cookbook', 'focus', 'fans', 'stared', 'star')
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        return $this->paginate($users);
    }

    public function applyTempDaren(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'value' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        //不存在关闭情况
        $value = 1;//$request->input('value');
        $list = User::whereIn('id', $arr_id)->get();
        foreach ($list as $user) {
            $user->is_temp_daren = $value;

            $vip_expired_at = $user->vip_expired_at ?: 0;
            if ($vip_expired_at) {
                if (strtotime($vip_expired_at) >= time()) {
                    $vip_expired_at = date('Y-m-d', strtotime("+3 month", strtotime($vip_expired_at)));
                } else {
                    $vip_expired_at = date('Y-m-d', strtotime("+3 month", time()));
                }
            } else {
                $vip_expired_at = date('Y-m-d', strtotime("+3 month", time()));
            }
            $user->is_vip = 1;
            $user->vip_expired_at = $vip_expired_at;
            $user->save();
        }
        return $this->success([]);
    }



}

